package com.song.luence;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.nio.file.FileSystems;

public class LuenceTest2 {

    //建立索引
    @Test
    public void index(){
        IndexWriter indexWriter = null ;
        try{
            //创建Directory
            Directory directory = FSDirectory.open(FileSystems.getDefault().getPath("F:\\SONG_WORKSPACE\\IDEA_WORKSPACE\\luence-core"));
            //创建 IndexWriter
            Analyzer analyzer = new StandardAnalyzer();
            IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
            indexWriter = new IndexWriter(directory,indexWriterConfig);
            indexWriter.deleteAll(); //清楚以前的index

            //要搜索的File路径
            File file = new File("F:\\SONG_WORKSPACE\\IDEA_WORKSPACE\\luence-data");

            File[] files = file.listFiles();

            for (File file1 : files){
                Document document = new Document();

                //为Document添加Field
               // document.add(new Field("content",new FileReader(file1), TextField.TYPE_NOT_STORED));  //java.io.FileReader@51dcb805  不是读取文件内容,只是一个文件对象

                BufferedReader bufferedReader = new BufferedReader(new FileReader(file1));
                String content = "";
                while ((content = bufferedReader.readLine()) != null) {
                    System.out.println(content);
                    document.add(new TextField("content", content, Field.Store.YES));
                }
                document.add(new Field("filename", file1.getName(), TextField.TYPE_STORED));
                document.add(new Field("filepath", file1.getAbsolutePath(), TextField.TYPE_STORED));

                //通过IndexWriter 添加文档到索引中
                indexWriter.addDocument(document);
            }

        }catch (Exception e){

        }finally {
            try {
                if (indexWriter != null) {
                    indexWriter.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //搜索

    @Test
    public void search(){
        DirectoryReader directoryReader = null ;
        String keyWords = "数据";
        try{
            //创建 Directory
            Directory directory = FSDirectory.open(FileSystems.getDefault().getPath("F:\\SONG_WORKSPACE\\IDEA_WORKSPACE\\luence-core"));
            //创建IndexReader
            directoryReader = DirectoryReader.open(directory);

            //创建IndexSearch
            IndexSearcher indexSearcher = new IndexSearcher(directoryReader);

            //创建搜索的 Query
            Analyzer analyzer = new StandardAnalyzer();

                //创建parser 确定搜索的内容，第一个参数为搜索的Field  比如索引filename、content域
            QueryParser queryParser = new QueryParser("content",analyzer);
            //创建query 表示搜索Field为content 的文档
            Query query = queryParser.parse(keyWords);

            //根据search搜索并返回TopDocs
            TopDocs topDocs = indexSearcher.search(query,10);
            System.out.println("查找到的文档有："+topDocs.totalHits);

            //根据TopDocs 获取 ScoreDoc对象
            ScoreDoc[] scoreDocs = topDocs.scoreDocs ;
            for (ScoreDoc scoreDoc : scoreDocs){

                //根据search 和 ScoreDoc 获取具体的Document对象
                Document document = indexSearcher.doc(scoreDoc.doc);

                //根据Document 对象 获取需要的值

                System.out.println(document.get("filename")+"  "+document.get("filepath"));
            }

        }catch (Exception e){

        }finally {
            try {
                if (directoryReader != null) {
                    directoryReader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {


        LuenceTest2 luenceTest2 = new LuenceTest2();
        luenceTest2.index();;
        luenceTest2.search();
    }
}
